package com.cd.university.config.security.authentication.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 邮件验证码的Provider
 * @author 陈栋
 * @create 2021/9/10 14:17
 */
public class EmailCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 把Authentication强转为EmailCodeAuthenticationToken
        EmailCodeAuthenticationToken authenticationToken = (EmailCodeAuthenticationToken) authentication;

        // 查找UserDetails
        UserDetails user = userDetailsService.loadUserByUsername(authenticationToken.getName());

        if (user==null) {
            throw new InternalAuthenticationServiceException("无法获得用户信息");
        }
        // 通过传进来的(EmailCodeAuthenticationToken) authentication构造一个新的authentication（认证过的）
        EmailCodeAuthenticationToken emailCodeAuthenticationToken = new EmailCodeAuthenticationToken(user.getAuthorities(), authentication.getPrincipal());
        emailCodeAuthenticationToken.setDetails(authentication.getDetails());
        return emailCodeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        /**
         * 确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同，或者是其超类或超接口。
         * 如果是，则返回true ； 否则返回false 。
         */
        return EmailCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
